import React, { useEffect } from "react";
import { Modal, Form, Input, message, Button, Select } from "antd";

interface CategoryValues {
  category_name: string;
  type: number;
}

interface CategoryModalProps {
  title: string;
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  defaultValue?: any;
}

const CategoryModal: React.FC<CategoryModalProps> = ({
  title,
  visible,
  onCancel,
  onOk,
  defaultValue,
}) => {
  const [form] = Form.useForm<CategoryValues>();

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
      form.resetFields();
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  useEffect(() => {
    if (Object.keys(defaultValue).length === 0) {
      form.resetFields();
    } else {
      form.setFieldsValue({
        ...defaultValue,
      });
    }
  }, [defaultValue, visible]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form}>
        <Form.Item
          label="物品类别"
          name="category_name"
          rules={[
            {
              required: true,
              whitespace: true,
              message: "请输入物品类别",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入物品类别" />
        </Form.Item>
        <Form.Item
          label="物品类别类型"
          name="type"
          rules={[
            {
              required: true,
              type: "number",
              message: "请选择物品类别类型",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Select placeholder="请选择物品类别类型">
            <Select.Option value={1}>耗材</Select.Option>
            <Select.Option value={2}>非耗材</Select.Option>
          </Select>
        </Form.Item>

        
      </Form>
    </Modal>
  );
};

export default CategoryModal;
